Variables
Table of Contentsβ
- Introduction to Variables
- Variable Declaration & Initialization
- Data Types
- Variable Scopes
- Type Conversion & Casting
- Final Variables
- Variable Naming Conventions
- Practical Examples
- Best Practices
1. Introduction to Variablesβ
Variables are named containers that store data in Java programs. They:
- Have a specific data type
- Occupies memory space
- Follow Java's naming conventions
- Have defined scope and lifetime
Key characteristics:
- Name: Identifier for the variable
- Type: Determines size and operations
- Value: Data stored in memory
- Memory Address: Location in RAM
2. Variable Declaration & Initializationβ
Declaration Syntaxβ
type identifier;
Initializationβ
identifier = value;
Combined Declaration & Initializationβ
type identifier = value;
Exampleβ
int age; // Declaration
age = 30; // Initialization
double pi = 3.14; // Combined
3. Data Typesβ
Primitive Typesβ
| Type | Size | Range | Default | Example |
|---|---|---|---|---|
byte | 8 bits | -128 to 127 | 0 | byte b = 100; |
short | 16 bits | -32,768 to 32,767 | 0 | short s = 500; |
int | 32 bits | -2Β³ΒΉ to 2Β³ΒΉ-1 | 0 | int i = 100000; |
long | 64 bits | -2βΆΒ³ to 2βΆΒ³-1 | 0L | long l = 10000000000L; |
float | 32 bits | Β±3.4eβ»Β³βΈ to Β±3.4eΒ³βΈ | 0.0f | float f = 3.14f; |
double | 64 bits | Β±1.7eβ»Β³β°βΈ to Β±1.7eΒ³β°βΈ | 0.0d | double d = 3.141592; |
char | 16 bits | Unicode characters | '\u0000' | char c = 'A'; |
boolean | 1 bit | true/false | false | boolean flag = true; |
Reference Typesβ
- Store references to objects
- Default value:
null - Examples:
String name = "Java";
int[] numbers = {1, 2, 3};
Object obj = new Object();
4. Variable Scopesβ
Class Variables (Static)β
class Counter {
static int count = 0; // Shared across all instances
}
Instance Variablesβ
class Person {
String name; // Unique to each instance
}
Local Variablesβ
void calculate() {
int result = 0; // Method-scoped
}
Block Variablesβ
for(int i=0; i<10; i++) { // Loop-scoped
System.out.println(i);
}
Scope Comparisonβ
| Scope | Declaration Location | Lifetime | Access Modifiers | Memory Allocation |
|---|---|---|---|---|
| Class | Inside class, with static | Class loading to unloading | Yes | Method Area |
| Instance | Inside class, no static | Object creation to GC | Yes | Heap |
| Local | Inside method/block | Block execution | No | Stack |
| Parameter | Method parameters | Method execution | No | Stack |
5. Type Conversion & Castingβ
Widening (Automatic)β
int i = 100;
long l = i; // Automatic conversion
Narrowing (Explicit Casting)β
double d = 100.04;
long l = (long) d; // Explicit cast
Type Promotion Rulesβ
byteβshortβintβlongβfloatβdoublecharβint
Exampleβ
byte b = 42;
char c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double result = (f * b) + (i / c) - (s * 0.1);
// b promoted to float, c to int, s to double
6. Final Variablesβ
final creates immutable references (constants)
final double PI = 3.14159;
final int MAX_USERS = 1000;
Rules:
- Must be initialized
- Cannot be reassigned
- Convention: UPPER_SNAKE_CASE
7. Variable Naming Conventionsβ
- Start with letter,
$, or_(not recommended) - Subsequent characters: letters, digits,
$,_ - Case-sensitive
- Avoid reserved keywords
- Follow camelCase convention
Examples:
int studentCount; // Good
String firstName; // Good
double accountBalance; // Good
int _temp; // Avoid
String $name; // Avoid
8. Practical Examplesβ
Example 1: Variable Usageβ
public class Circle {
// Class variable
static final double PI = 3.14159;
// Instance variable
double radius;
public Circle(double r) {
// Parameter variable
radius = r;
}
public double area() {
// Local variable
double result = PI * radius * radius;
return result;
}
public static void main(String[] args) {
// Local variable
Circle myCircle = new Circle(5.0);
System.out.println("Area: " + myCircle.area());
}
}
Example 2: Type Castingβ
public class TypeConversion {
public static void main(String[] args) {
int intValue = 100;
// Widening conversion
long longValue = intValue;
// Narrowing conversion
byte byteValue = (byte) intValue;
System.out.println("Original int: " + intValue);
System.out.println("Widened long: " + longValue);
System.out.println("Narrowed byte: " + byteValue);
// Special case: float to int
float floatValue = 123.456f;
int truncated = (int) floatValue;
System.out.println("Truncated float: " + truncated);
}
}
Example 3: Scope Demonstrationβ
public class ScopeDemo {
static int classVar = 10; // Class-level
int instanceVar = 20; // Instance-level
public void demoMethod(int paramVar) { // Parameter
int localVar = 30; // Method-level local
if(true) {
int blockVar = 40; // Block-level
System.out.println("Block variable: " + blockVar);
}
// blockVar not accessible here
System.out.println("Local variable: " + localVar);
System.out.println("Parameter: " + paramVar);
}
public static void main(String[] args) {
ScopeDemo demo = new ScopeDemo();
demo.demoMethod(50);
System.out.println("Class variable: " + classVar);
System.out.println("Instance variable: " + demo.instanceVar);
}
}
9. Best Practicesβ
- Initialize variables during declaration
- Use meaningful names (avoid single-letter names except in loops)
- Declare variables close to their usage
- Limit variable scope as much as possible
- Use
finalfor constants - Avoid public instance variables (use encapsulation)
- Prefer primitive types for performance-critical code
- Be cautious with implicit type conversions
- Use
varfor local variables when type is obvious (Java 10+)
var list = new ArrayList<String>(); // Type inferred
- Avoid global variables where possible
Common Pitfallsβ
- Using uninitialized local variables
- Shadowing variables (local vs instance)
- Memory leaks with reference types
- Overflow/underflow in numeric operations
- Precision loss in floating-point operations